package com.loan.market.ui

import android.content.Context
import android.content.Intent
import android.view.ViewGroup
import android.widget.ImageView
import coil.load
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.loan.market.R
import com.loan.market.base.BaseBindingFragment
import com.loan.market.bean.Product
import com.loan.market.databinding.FragmentProductBinding
import com.loan.market.event.LoginEvent
import com.loan.market.event.LogoutEvent
import com.loan.market.http.ApiService
import com.loan.market.http.getHttpMap
import com.loan.market.http.request
import com.loan.market.util.UserUtil
import com.loan.market.util.formatAmount
import com.loan.market.util.http
import com.loan.market.util.jump
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class ProductFragment : BaseBindingFragment<FragmentProductBinding>() {

    private fun formatNum(num: Int?): String {
        if (num == null) return "0"
        return if (num < 1_000) {
            num.toString()
        } else if (num in 1_000..999999) {
            return (num / 1000).toString() + "k"
        } else if (num in 1_000_000..999999999) {
            return (num / 1_000_000).toString() + "m"
        } else {
            return (num / 1_000_000_000).toString() + "b"
        }
    }

    private val quickAdapter by lazy {
        object : BaseQuickAdapter<Product, QuickViewHolder>() {
            override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: Product?) {
                holder.getView<ImageView>(R.id.iv_logo).load(item?.productLogoUrl)
                holder.setGone(R.id.iv_logo, item?.productLogoUrl.isNullOrEmpty())
                holder.setText(R.id.tv_name, item?.productName)
                holder.setText(R.id.tv_like, formatNum(item?.likes))
                holder.setText(R.id.tv_amount, item?.maxAmount.formatAmount())
                if (item?.currency.isNullOrEmpty()) {
                    holder.setText(R.id.tv_max, getString(R.string.amount))
                } else {
                    holder.setText(R.id.tv_max, getString(R.string.amount) + " (" + item?.currency + ")")
                }
                holder.setText(R.id.tv_term, getString(R.string.term) + item?.termMin + "-" + item?.termMax + " " + item?.termUnit)
                val tna = (item?.annualRate?.toFloat() ?: 0f) / (item?.rateBasePoints ?: 1)
                holder.setText(R.id.tv_rate, "TNA: " + (tna * 100).toString().formatAmount() + "%")
                holder.setImageResource(R.id.iv_like, if (item?.ilike == true) R.mipmap.icon_liked else R.mipmap.icon_like)
                holder.setTextColor(R.id.tv_like, requireActivity().getColor(if (item?.ilike == true) R.color.color_accent else R.color.color_999))
            }

            override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
                return QuickViewHolder(R.layout.item_product, parent)
            }
        }
    }

    override fun getViewBinding(): FragmentProductBinding {
        return FragmentProductBinding.inflate(layoutInflater)
    }

    private var index = 0
    private var type = ""

    override fun initUi() {
        EventBus.getDefault().register(this)
        index = arguments?.getInt("index", 0) ?: 0
        type = arguments?.getString("type", "") ?: ""
        binding.rvProduct.adapter = quickAdapter
    }

    override fun initEvent() {
        quickAdapter.setOnItemClickListener { adapter, view, position ->
            if (!UserUtil.isLogin()) {
                startActivity(Intent(requireActivity(), LoginActivity::class.java))
                return@setOnItemClickListener
            }
            val product = adapter.getItem(position)
            http(onFinish = ::dismissLoading) {
                showLoading()
                val map = getHttpMap(206)
                map["productId"] = product?.productId
                request<Any>(map, ApiService.path3)
                requireActivity().jump(product?.clickUrl, product?.productId)
            }
        }
        quickAdapter.addOnItemChildClickListener(R.id.fl_like) { adapter, view, position ->
            if (!UserUtil.isLogin()) {
                startActivity(Intent(requireActivity(), LoginActivity::class.java))
                return@addOnItemChildClickListener
            }
            val product = adapter.getItem(position) ?: return@addOnItemChildClickListener
            http {
                val map = getHttpMap(205)
                map["productId"] = product.productId
                map["likesOrNot"] = if (product.ilike) 0 else 1
                request<Any>(map, ApiService.path3)
                product.ilike = !product.ilike
                if (product.ilike) {
                    product.likes++
                } else {
                    product.likes--
                }
                quickAdapter.notifyItemChanged(position, "like")
            }
        }
    }

    override fun initData() {
        http(onFinish = {
            if (index == 0) dismissLoading()
        }) {
            if (index == 0) showLoading()
            val map = getHttpMap(204)
            map["category"] = type
            val list = request<List<Product>>(map, ApiService.path2)
            quickAdapter.submitList(list)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun login(loginEvent: LoginEvent) {
        initData()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun logout(logoutEvent: LogoutEvent) {
        initData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }
}